<template>
	<payModal />
</template>

<script>
	import payModal from "@/components/payModal.vue";
	import errCode from '@/common/errorCode.js'
	import {
		setCloseFunction
	} from '@/common/modalHandler.js'
	import {
		Login,
		Books,
		Users
	} from "@/request/api.js"
	const {
		NovelExtension,
		getNovelManager
	} = tt;

	const NovelExtensionOption = {
		data() {
			return {
				query: {},
				novel: null,
				bookId: 0,
				pageChapterId: 0,
				userInfo: {}
			}
		},
		async onLoad(option) {
			this.query = option
			console.log(option,'option')
			this.$globalData.searchKeywordId = option.search_keyword_id
			this.cacheBookId() //缓存书籍id
			await this.login() //登录
			this.novel = getNovelManager()

			// 错误监听
			this.novel.onNovelError((e) => {
				const index = errCode.findIndex(item => item.code == e.errorCode)
				const msg = index !== -1 ? errCode[index].message : '页面启动错误'
				this.$u.toast(msg)
			})
			
			//监听用户进入阅读器()
			this.novel.onClickStartReading(async (e)=>{
				//保存阅读历史
				// let data = {
				// 	book_id: 851308,
				// 	chapter_id: 423671,
				// 	read_progress: 80,
				// 	read_line: 0
				// }
				// await Books.SaveHistory(data)
				// uni.removeStorageSync('outBookId')
				
			})
			
			//监听用户退出阅读器
			this.novel.onBackPlugin(async (e)=>{
				this.$u.toast('onBackPlugin')
				console.log(e,'onBackPlugin');
				// //离开保存阅读历史
				// let data = {
				// 	book_id: 846014,
				// 	chapter_id: 380454,
				// 	read_progress: 0,
				// 	read_line: 0
				// }
				// await Books.SaveHistory(data)
				// uni.removeStorageSync('outBookId')
				
			})

			// 是否加入书架
			this.novel.onClickBookShelf(async (e) => {
				if (e.ShelfStatus === 1) {
					let res = await Books.Addbooks(uni.getStorageSync('outBookId'))
					// tt.showToast({
					// 	title: '加入书架'
					// })
				} else {				
					let book_id = []
					book_id.push(uni.getStorageSync('outBookId'))
					let res = await Books.DelBookCase(book_id)
					// tt.showToast({
					// 	title: '移除书架'
					// })
				}
			})
			
			// 书币模式授权
			this.novel.showAutoUnlockAuth({
				onConfirm: () => {
					tt.showToast({
						title: '授权成功'
					})
				},
				onCancel: () => {
					tt.showToast({
						title: '授权取消'
					})
				}
			});
			
			// 自定义书币扣费模式
			this.novel.onUnlockChapterShow((params)=>{
				console.log(params,'params')
			    const chapterId = params.chapterId
			    // 自定义解锁逻辑，如书币是否充足
			    const canUnlock = 1
			    if(canUnlock){
			        // 解锁
			        return {
			            unlockChapterList:[{chapterId:params.chapterId}]
			        }
			    }else {
			        // 不解锁
			        return {unlockChapterList:[]}
			    }
			})


			// 添加桌面
			this.novel.onAddDesktop((res) => {
				tt.showToast({
					title: '添加桌面成功'
				})
			})
			
			

			// 唤起解锁弹窗
			this.novel.onClickUnlockPrimaryButton((res) => {
				const {
					showPayModal,
					closePayModal,
					chapterId
				} = res
				// 如果是短篇的话直接拉起充值模板
				showPayModal()
				setCloseFunction(closePayModal);
			})
		
		},
		
		
		// 分享
		onShareAppMessage() {
			return {
				title: "观看精彩后续内容",
				path: `/pages/novel_plugin/index?book_id=${this.query.book_id}&chapter_id=${this.chapter_id}&search_keyword_id=${this.$globalData.searchKeywordId}`,
			}
		},

		methods: {
			// 登录行
			login() {
				tt.login({
					provider: 'toutiao',
					force: true,
					success: async (loginres) => {
						await Login.login({
							code: loginres.code,
							passphrases: this.$globalData.searchKeywordId
						})
						// await this.getBookDetail()
						this.getUserInfo()
					}
				})
			},

			//获取用户信息
			async getUserInfo() {
				const result = await Users.Userinfo()
			},

			// 广告
			registerCallback() {
				if (this.query.hasOwnProperty('clickid')) {
					let {
						id: book_id,
						chapter_id,
						pen_name,
						...rest
					} = query
					const data = {
						book_id,
						open_id: 0,
						...rest
					}
					Books.Advertising(data)
				}
			},

			// 缓存书籍id
			cacheBookId() {
				if (this.query.hasOwnProperty('adid')) {
					uni.setStorageSync("keywords", this.$globalData.searchKeywordId)
					uni.setStorageSync("bookId", this.query.book_id)
					uni.setStorageSync('timestamp', new Date().getTime())
				}
			},

			// 获取书籍类型
			async getBookDetail(){
				let result = await Books.detail(this.query.book_id)
				if(result.status_code == 401){
					this.login()
				}else{
					// 获取书籍类型
				}
			},
			
			
			
			
		},
		service: {
			// 获取内容
			queryContentsInfo(res) {
				console.log('queryContentsInfo', res)
				uni.setStorageSync('outBookId',res.outBookId)
				return {
					chapterList: [{
							chapterId: '8',
							status: 0,
						},
						{
							chapterId: '9',
							status: 0,
						},
					]
				}
			},
			//读后推荐
			queryRecommendedBooks(a){
				console.log(a,'aaaa');
				return["r7484080395663903011",]
				
			},
			// 获取高级模式解锁状态
			queryLockModalText(id) {
				return {
					title: '充值会员，解锁章节',
					primary: '充值会员',
				}
			},
		},
	};

	NovelExtension(NovelExtensionOption)

	export default {
		components: {
			payModal
		},
		...NovelExtensionOption
	}
</script>